﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Base;

using DevExpress.Utils;
using DevExpress.Utils.Design;
using DevExpress.XtraEditors.Controls;
using System.Runtime.InteropServices;
using Lamex.mMES.Common;
using System.IO;
using Lamex.Interface;

namespace Lamex.mMES.UI
{
    public partial class frmMES_Project_Log_Timeline : frmBaseChild
    {
        public static Form fm = null;
        public static string strPic;
        public static int X, Y;

        //自定义显示日历
        //https://github.com/DevExpress-Examples/how-to-customize-cell-appearance-in-calendarcontrol-and-dateedit-cellstyleprovider-t352638

        string strSql;
        DataTable dt;
        string strCurDate, imageName; 

        public frmMES_Project_Log_Timeline()
        {
            InitializeComponent();

            this.panel1.MouseWheel += new MouseEventHandler(panel1_MouseWheel);
            this.pictureBox1.MouseWheel += new MouseEventHandler(pictureBox1_MouseWheel);
            this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        }

        private void frmMES_Project_Log_Timeline_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            //测试无效，问题未解决，放在InitializeComponent后也不行
            //也可能是解决了panel，但未解决pictureBox
            //PanelScrollHelper.InitializePanelScroll(panel1);

            gridView1.OptionsBehavior.Editable = false;

            calendarControl1.RowCount = 2;//纵向显示多月，垂直显示月份数
            calendarControl1.ShowWeekNumbers = true;//显示周次
            calendarControl1.ShowYearNavigationButtons = DevExpress.Utils.DefaultBoolean.True;
            calendarControl1.FirstDayOfWeek = DayOfWeek.Sunday;//周起始日
            //calendarControl1.DrawCellLines = true;//加网格线
            //calendarControl1.CalendarTimeEditing = true;//显示时钟

            calendarControl1.MinValue = System.DateTime.Now.AddYears(-1);
            calendarControl1.MaxValue = System.DateTime.Now.AddYears(1);

            calendarControl1.DateTime = new DateTime(2020, 7, 22);
            //calendarControl1.DateTime = System.DateTime.Now;
            calendarControl1.CellStyleProvider = new CustomCellStyleProvider();

            ContextButton cb = new ContextButton()
            {
                Alignment = ContextItemAlignment.TopNear,
                Visibility = ContextItemVisibility.Hidden,
                //Caption = "AAA"
            };

            //calendarControl1.CellSize = new Size(50, 50);//24x24
            //calendarControl1.CellSize = new Size(66, 66);//16x16
            calendarControl1.CellSize = new Size(39, 36);//16x16
            calendarControl1.ContextButtons.Add(cb);
            calendarControl1.ContextButtonCustomize += CalendarControl1_ContextButtonCustomize;

            //按时间轴刷新界面
            //resetControlAndGetData_ByCalendar();
            resetControlAndGetData_ByTimeline();
        }

        private void frmMES_Project_Log_Timeline_Resize(object sender, EventArgs e)
        {
            if (radioGroup1.SelectedIndex == -1)
            {
                splitContainerControl1.SplitterPosition = 297;
                splitContainerControl2.SplitterPosition = this.Width - splitContainerControl1.SplitterPosition - this.Height;

                pictureBox1.Width = panel1.Width - 12;
                pictureBox1.Height = panel1.Height - 12;
                pictureBox1.Location = new Point(6, 6);
            }
            else
            {
                splitContainerControl1.SplitterPosition = this.Width / 3;
                splitContainerControl2.SplitterPosition = this.Width / 3;
            }
        }

        private void CalendarControl1_ContextButtonCustomize(object sender, CalendarContextButtonCustomizeEventArgs e)
        {
            string holidayText;
            if (ProjectLogData.HaveLogData(e.Cell.Date, out holidayText))
            {
                e.Item.Glyph = global::Lamex.mMES.Properties.Resources.apply_16x16;//对勾
                //e.Item.Glyph = global::Lamex.mMES.Properties.Resources.iconsetrating4_16x16;//蓝色信号
                //e.Item.Glyph = global::Lamex.mMES.Properties.Resources.iconsetsigns3_16x16;//圆点
                e.Item.Visibility = ContextItemVisibility.Visible;
                e.Item.ToolTip = holidayText;
                e.Item.ShowToolTips = true;
                //e.Item.Name = holidayText.Substring(0,2);
                e.Cell.Description = "AAA";
            }
        }

        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            resetControlAndGetData();
        }

        //初始化控件及数据
        private void resetControlAndGetData()
        {
            ucTimeLine1.Items = null;
            ucTimeLine2.Items = null;
            ucTimeLine3.Items = null;

            //calendarControl1.ContextButtons.Clear();
            gridControl1.DataSource = null;
            pictureBox1.Image = null;

            if (radioGroup1.SelectedIndex == 0)
            {
                resetControlAndGetData_ByTimeline();
            }
            else
            {
                resetControlAndGetData_ByCalendar();
            }
            sbtnView.Focus();//radioGroup1失去焦点，避免鼠标滚轮触发显示方式切换
        }

        //初始化控件及数据_日历
        private void resetControlAndGetData_ByCalendar()
        {
            splitContainerControl1.SplitterPosition = 297;
            splitContainerControl2.SplitterPosition = this.Width - splitContainerControl1.SplitterPosition - this.Height;

            ucTimeLine1.Visible = false;
            ucTimeLine1.Dock = DockStyle.None;
            ucTimeLine2.Visible = false;
            ucTimeLine2.Dock = DockStyle.None;
            ucTimeLine3.Visible = false;
            ucTimeLine3.Dock = DockStyle.None;

            calendarControl1.Visible = true;
            calendarControl1.Dock = DockStyle.Fill;
            gridControl1.Visible = true;
            gridControl1.Dock = DockStyle.Fill;
            panel1.Visible = true;
            panel1.Dock = DockStyle.Fill;

            groupControl1.Text = "项目日历";
            groupControl2.Text = "项目明细";
            groupControl3.Text = "项目记录或成果";
        }

        // 初始化控件及数据_时间轴
        private void resetControlAndGetData_ByTimeline()
        {
            splitContainerControl1.SplitterPosition = this.Width / 3;
            splitContainerControl2.SplitterPosition = this.Width / 3;

            ucTimeLine1.Visible = true;
            ucTimeLine1.Dock = DockStyle.Fill;
            ucTimeLine2.Visible = true;
            ucTimeLine2.Dock = DockStyle.Fill;
            ucTimeLine3.Visible = true;
            ucTimeLine3.Dock = DockStyle.Fill;

            calendarControl1.Visible = false;
            calendarControl1.Dock = DockStyle.None;
            gridControl1.Visible = false;
            gridControl1.Dock = DockStyle.None;
            panel1.Visible = false;
            panel1.Dock = DockStyle.None;

            groupControl1.Text = "项目时间轴（当前周）";
            groupControl2.Text = "项目时间轴（前一周）";
            groupControl3.Text = "项目时间轴（前两周）";

            DateTime now = DateTime.Now;

            String strDT1, strDT2;

            strDT1 = now.AddDays(-(int)now.DayOfWeek + 1).ToString("yyyy/MM/dd");
            strDT2 = now.AddDays(7 - (int)now.DayOfWeek).ToString("yyyy/MM/dd");
            AddDataToTimeLine(GetTimeLineData(strDT1, strDT2), ucTimeLine1);

            strDT1 = now.AddDays(-(int)now.DayOfWeek + 1 -7).ToString("yyyy/MM/dd");
            strDT2 = now.AddDays(7 - (int)now.DayOfWeek -7).ToString("yyyy/MM/dd");
            AddDataToTimeLine(GetTimeLineData(strDT1, strDT2), ucTimeLine2);

            strDT1 = now.AddDays(-(int)now.DayOfWeek + 1 - 7 * 2).ToString("yyyy/MM/dd");
            strDT2 = now.AddDays(7 - (int)now.DayOfWeek - 7 * 2).ToString("yyyy/MM/dd");
            AddDataToTimeLine(GetTimeLineData(strDT1, strDT2), ucTimeLine3);

//            string strSql2 = @"SELECT FORMAT(DEV_LOG_DATE,'yyyy/M/d') + ' ' + PROJECT_NAME AS Title,
//DEV_LOG_DESC AS Details
//FROM DPT_Project_Dev_Log
//WHERE DEV_LOG_DATE>='" + now.AddDays(-(int)now.DayOfWeek + 1 - 7) + @"'
//AND DEV_LOG_DATE<='" + now.AddDays(7 - (int)now.DayOfWeek - 7) + @"'
//ORDER BY DEV_LOG_DATE DESC";
//            AddDataToTimeLine(strSql2, ucTimeLine2);

//            string strSql3 = @"SELECT FORMAT(DEV_LOG_DATE,'yyyy/M/d') + ' ' + PROJECT_NAME AS Title,
//DEV_LOG_DESC AS Details
//FROM DPT_Project_Dev_Log
//WHERE DEV_LOG_DATE>='" + now.AddDays(-(int)now.DayOfWeek + 1 - 7 * 2) + @"'
//AND DEV_LOG_DATE<='" + now.AddDays(7 - (int)now.DayOfWeek - 7 * 2) + @"'
//ORDER BY DEV_LOG_DATE DESC";
//            AddDataToTimeLine(strSql3, ucTimeLine3);
        }

        private static string GetTimeLineData(String strDT1, String strDT2)
        {
            string strSql = @"SELECT FORMAT(DEV_LOG_DATE,'yyyy/M/d') + ' ' + PROJECT_NAME AS Title,
DEV_LOG_DESC AS Details
FROM DPT_Project_Dev_Log
WHERE DEV_LOG_DATE>='" + strDT1 + @"'
AND DEV_LOG_DATE<='" + strDT2 + @"'
ORDER BY DEV_LOG_DATE DESC";
            return strSql;
        }

        private void AddDataToTimeLine(string strSql, HZH_Controls.Controls.UCTimeLine ucTimeLine)
        {
            DataTable dt = BaseBuildSql.GetDataTableBySql(strSql);
            if (dt.Rows.Count > 0 && dt != null)
            {
                //加载显示时间轴
                HZH_Controls.Controls.TimeLineItem[] items;
                items = new HZH_Controls.Controls.TimeLineItem[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    items[i] = new HZH_Controls.Controls.TimeLineItem()
                    {
                        //Title = String.Format(dt.Rows[i]["DEV_LOG_DATE"].ToString(), "yyyy-M-d"),
                        Title = dt.Rows[i]["Title"].ToString(),
                        Details = dt.Rows[i]["Details"].ToString()
                    };
                }
                ucTimeLine.Items = items;
            }
        }

        //因单击事件与日历本身单击功能冲突，所以选用双击
        private void calendarControl1_DoubleClick(object sender, EventArgs e)
        {
            gridControl1.DataSource = null;
            strCurDate = calendarControl1.SelectedRanges.Start.ToString();

            //MessageBox.Show(calendarControl1.SelectedRanges.Max().ToString());
            //MessageBox.Show(calendarControl1.SelectedRanges.Start.ToString());
            string strSql = @"SELECT a.PROJECT_NAME AS 项目名称,PROJECT_LEADER AS 项目负责,DEV_LOG_DESC AS 日志描述,
DEV_LOG_STATE AS 项目状态,IMAGE_NAME AS 日志图片
FROM DPT_Project_Dev_Log AS a,DPT_Project_Item_List AS b
WHERE DEV_LOG_DATE='" + strCurDate + @"'
AND a.PROJECT_NAME=b.PROJECT_NAME";

            DataTable dt = BaseBuildSql.GetDataTableBySql(strSql);
            gridControl1.DataSource = dt;
        }

        private void splitContainerControl2_SplitterPositionChanged(object sender, EventArgs e)
        {
            pictureBox1.Width = panel1.Width - 12;
            pictureBox1.Height = panel1.Height - 12;
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            int iRow = gridView1.FocusedRowHandle;

            #region 禁用数据库保存读取图片，已改为外部调用图片

            //            string CurCellValue = gridView1.FocusedValue.ToString();//gridView当前选定值
            //            string strProjectName = gridView1.GetRowCellDisplayText(iRow, "项目名称").ToString();

            //            string strSql = @"SELECT IMAGE_NAME,DEV_LOG_IMAGE
            //FROM DPT_Project_Dev_Log 
            //WHERE PROJECT_NAME='" + strProjectName + @"'
            //AND DEV_LOG_DATE='" + strCurDate + @"'";

            //            DataTable dt = BaseBuildSql.GetDataTableBySql(strSql);

            //            if (dt.Rows.Count > 0)
            //            {
            //                imageName = dt.Rows[0]["IMAGE_NAME"].ToString();

            //                //从数据库加载图片
            //                if (string.IsNullOrEmpty(imageName))
            //                {
            //                    Byte[] imgbt = (Byte[])dt.Rows[0]["DEV_LOG_IMAGE"];
            //                    if (imgbt.Length != 0)
            //                    {
            //                        MemoryStream stream = new MemoryStream(imgbt);
            //                        Image img = Image.FromStream(stream);
            //                        pictureBox1.Image = img;
            //                        stream.Close();
            //                    }
            //                }

            //                //从指定路径加载图片
            //                else
            //                {
            //                    pictureBox1.Image = Image.FromFile(@"\\TX-FS10\tx-fs1\IMA\MES\ShareResource\Project_Log_Image\" + imageName + ".jpg");
            //                }
            //            }

            #endregion

            imageName = gridView1.GetRowCellDisplayText(iRow, "日志图片").ToString();
            pictureBox1.Image = Image.FromFile(@"\\TX-FS10\tx-fs1\IMA\MES\ShareResource\Project_Log_Image\" + imageName);
            //pictureBox1.Image = Image.FromFile(@"\\TX-FS10\tx-fs1\IMA\MES\ShareResource\Project_Log_Image\" + imageName + ".jpg");

            pictureBox1.Width = panel1.Width - 12;
            pictureBox1.Height = panel1.Height - 12;
            pictureBox1.Location = new Point(6, 6);
        }
        private void sbtnView_Click(object sender, EventArgs e)
        {
            resetControlAndGetData();
        }

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        #region 双击图片放大或还原
        private void panel1_DoubleClick(object sender, EventArgs e)
        {
            resetPictureBoxSize();
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            resetPictureBoxSize();
        }

        private void resetPictureBoxSize()
        {
            if (splitContainerControl1.SplitterPosition == 0)
            {
                splitContainerControl1.SplitterPosition = 297;
                splitContainerControl2.SplitterPosition = this.Width - splitContainerControl1.SplitterPosition - this.Height;
            }
            else
            {
                splitContainerControl1.SplitterPosition = 0;
                splitContainerControl2.SplitterPosition = 0;
            }
        }

        #endregion

        #region 图片放大缩小平移

        private bool isMouseDown = false;
        private Point mouseOffset;

        private void panel1_MouseWheel(object sender, MouseEventArgs e)
        {
            double step = 1.05;
            if (e.Delta > 0)
            {
                if (pictureBox1.Height >= Screen.PrimaryScreen.Bounds.Height * 10)
                    return;
                pictureBox1.Height = (int)(pictureBox1.Height * step);
                pictureBox1.Width = (int)(pictureBox1.Width * step);

                int px = Cursor.Position.X - pictureBox1.Location.X;
                int py = Cursor.Position.Y - pictureBox1.Location.Y;
                int px_add = (int)(px * (step - 1.0));
                int py_add = (int)(py * (step - 1.0));
                pictureBox1.Location = new Point(pictureBox1.Location.X - px_add, pictureBox1.Location.Y - py_add);
                Application.DoEvents();
            }
            else
            {
                pictureBox1.Height = (int)(pictureBox1.Height / step);
                pictureBox1.Width = (int)(pictureBox1.Width / step);

                int px = Cursor.Position.X - pictureBox1.Location.X;
                int py = Cursor.Position.Y - pictureBox1.Location.Y;
                int px_add = (int)(px * (1.0 - 1.0 / step));
                int py_add = (int)(py * (1.0 - 1.0 / step));
                pictureBox1.Location = new Point(pictureBox1.Location.X + px_add, pictureBox1.Location.Y + py_add);
                Application.DoEvents();
            }
        }

        private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
            double step = 1.05;
            if (e.Delta > 0)
            {
                if (pictureBox1.Height >= Screen.PrimaryScreen.Bounds.Height * 10)
                    return;
                pictureBox1.Height = (int)(pictureBox1.Height * step);
                pictureBox1.Width = (int)(pictureBox1.Width * step);

                int px = Cursor.Position.X - pictureBox1.Location.X;
                int py = Cursor.Position.Y - pictureBox1.Location.Y;
                int px_add = (int)(px * (step - 1.0));
                int py_add = (int)(py * (step - 1.0));
                pictureBox1.Location = new Point(pictureBox1.Location.X - px_add, pictureBox1.Location.Y - py_add);
                Application.DoEvents();
            }
            else
            {
                pictureBox1.Height = (int)(pictureBox1.Height / step);
                pictureBox1.Width = (int)(pictureBox1.Width / step);

                int px = Cursor.Position.X - pictureBox1.Location.X;
                int py = Cursor.Position.Y - pictureBox1.Location.Y;
                int px_add = (int)(px * (1.0 - 1.0 / step));
                int py_add = (int)(py * (1.0 - 1.0 / step));
                pictureBox1.Location = new Point(pictureBox1.Location.X + px_add, pictureBox1.Location.Y + py_add);
                Application.DoEvents();
            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown)
            {
                int left = pictureBox1.Left + e.X - mouseOffset.X;
                int top = pictureBox1.Top + e.Y - mouseOffset.Y;
                pictureBox1.Location = new Point(left, top);
            }
            //不能在MouseMove事件中关闭，因为打开时间
            if (fm != null)
            {
                //没调好不起作用
                timer1.Start();
                timer1.Stop();
            }
        }



        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = false;
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseOffset.X = e.X;
                mouseOffset.Y = e.Y;
                isMouseDown = true;
            }
            else if (e.Button == MouseButtons.Right)//右键（右击）
            {
                pictureBox1.Width = panel1.Width - 12;
                pictureBox1.Height = panel1.Height - 12;
                pictureBox1.Location = new Point(6, 6);
            }
        }

        #endregion

    }
}

    public static class ProjectLogData
    {
        public static bool HaveLogData(DateTime dateTime, out string LogText)
        {
            LogText = "";
            ////New Year's Day
            //if (dt.Day == 1 && dt.Month == 1) holidayText = "New Year's Day";
            ////Independence Day
            //if (dt.Day == 4 && dt.Month == 7) holidayText = "Independence Day";
            ////Veterans Day
            //if (dt.Day == 11 && dt.Month == 11) holidayText = "Veterans Day";
            ////Christmas
            //if (dt.Day == 25 && dt.Month == 12) holidayText = "Christmas";

//            string strSql = @"SELECT TOP 1 PROJECT_NAME + DEV_LOG_DESC AS Title
//FROM DPT_Project_Dev_Log
//WHERE DEV_LOG_DATE='" + dateTime.ToString() + @"'";

            string strSql = @"SELECT PROJECT_NAME  + char(13) + char(10) + DEV_LOG_DESC AS Title
FROM DPT_Project_Dev_Log
WHERE DEV_LOG_DATE='" + dateTime.ToString() + @"'";

            DataTable dt = BaseBuildSql.GetDataTableBySql(strSql);

            if (dt.Rows.Count > 0 && dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if(i==0)
                    {
                        LogText = "P" + (i+1).ToString() + ". " + dt.Rows[i]["Title"].ToString();
                    }
                    else
                    {
                        LogText = LogText + "\r\n\r\nP" + (i + 1).ToString() + ". " + dt.Rows[i]["Title"].ToString();
                    }
                }
            }

            return !string.IsNullOrEmpty(LogText);

        }
    }

    public class CustomCellStyleProvider : ICalendarCellStyleProvider
    {
        static Font font;
        public void UpdateAppearance(CalendarCellStyle cell)
        {
            string holidayText;
            if (ProjectLogData.HaveLogData(cell.Date, out holidayText))
            {
                cell.Appearance.ForeColor = Color.Green;
                if (font == null)
                {
                    font = new Font(cell.Appearance.Font, FontStyle.Bold);
                }
                cell.Appearance.Font = font;

                //不改变底色，避免无法区分当前选择日期
                //if (cell.Active)
                //    cell.Appearance.BackColor = Color.HotPink;
                //else
                //    cell.Appearance.BackColor = Color.LightPink;
            }
        }
    }
